// pages/cart/cart.js
import store from '../../store/index.js'
import {add,reduce,remove,clear} from '../../action/index.js'
import silcepage from '../../listsilce.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
  list:[],
  isture:null,
  likelist:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  const page = (Math.random() * 6).toFixed(0)
  this.setData({
    list: store.getState().cartlist.cartlist,
    likelist: silcepage(page, 10)
  })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const page = (Math.random() * 6).toFixed(0)
    this.setData({
      list: store.getState().cartlist.cartlist,
      likelist: silcepage(page, 10)
    })
    const num = this.data.list.reduce((result, item) => {
      result = result + item.count
      return result
    }, 0)
    wx.setTabBarBadge({
      index: 2,
      text: `${num}`
    })
  },
  addcount(e){
    const id = e.currentTarget.dataset.id
    store.dispatch(add(id))
     store.subscribe(add)
    this.setData({
      list: store.getState().cartlist.cartlist
    })
    const num=this.data.list.reduce((result,item)=>{
     result=result+item.count
      return result
    },0)
    wx.setTabBarBadge({
      index: 2,
      text: `${num}`
    })
  },
  reducecount(e) {
    const id = e.currentTarget.dataset.id
    store.dispatch(reduce(id))
    store.subscribe(reduce)
    this.setData({
      list: store.getState().cartlist.cartlist
    })
    const num = this.data.list.reduce((result, item) => {
      result = result + item.count
      return result
    }, 0)
    wx.setTabBarBadge({
      index: 2,
      text: `${num}`
    })
  },
  removeproduct(e) {
    const id = e.currentTarget.dataset.id
    store.dispatch(remove(id))
    store.subscribe(remove)
    this.setData({
      list: store.getState().cartlist.cartlist
    })
    const num = this.data.list.reduce((result, item) => {
      result = result + item.count
      return result
    }, 0)
    wx.setTabBarBadge({
      index: 2,
      text: `${num}`
    })
  },
 emptycart(){
   store.dispatch(clear())
   store.subscribe(clear)
   this.setData({
     list: store.getState().cartlist.cartlist
   })
   const num = this.data.list.reduce((result, item) => {
     result = result + item.count
     return result
   }, 0)
   wx.setTabBarBadge({
     index: 2,
     text: `${num}`
   })
 },
 godetail(e){
   const item = JSON.stringify(e.currentTarget.dataset.item)
   wx.navigateTo({
     url: `/pages/detail/detail?item=${item}`
   })
 } 
 ,
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})